#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define LISTEN_QUEUE_NUM 20
class EpollServe;
struct Func;
// 封装套接字
class Sock
{
public:
    friend Func;
    friend EpollServe;
    Sock() = default;
    int Creat()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock < 0)
        {
            std::cout << "sock fail" << std::endl;
            exit(1);
        }
        _sock = sock;
        return sock;
    }
    bool Bind()
    {
        sockaddr_in serve;
        memset(&serve, 0, sizeof(serve));
        serve.sin_addr.s_addr = inet_addr("0.0.0.0");
        serve.sin_family = AF_INET;
        serve.sin_port = htons(_port);
        int ret = bind(_sock, (sockaddr *)(&serve), sizeof(serve));
        if(ret < 0)
        {
            std::cout << "bind fail" << std::endl;
            exit(2);
        }
        return true;
    }
    void Listen()
    {
        int ret = listen(_sock, LISTEN_QUEUE_NUM);
        if(ret < 0)
        {
            std::cout << "listen fail" << std::endl;
            exit(3);
        }
    }
    int Accept()
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int sock = accept(_sock, (sockaddr *)(&client), &len);
        if(sock < 0)
        {
            std::cout << "accept fail" << std::endl;
            exit(4);
        }
        return sock;
    }
    void Connect(int sock, uint16_t port, std::string& ip)
    {
        sockaddr_in serve;
        serve.sin_addr.s_addr = inet_addr(ip.c_str());
        serve.sin_family = AF_INET;
        serve.sin_port = htons(port);
        socklen_t len = sizeof(serve);
        int ret = connect(sock, (sockaddr *)(&serve), len);
        if(ret < 0)
        {
            std::cout << "connect fail" << std::endl;
            exit(5);
        }
    }
    ~Sock()
    {
        if(_sock > 0)
            close(_sock);
    }

private:
    int _sock;
    uint16_t _port = 8080;
};
